package com.tarry.socket.blocked;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Slf4j
public class Client {
    private final String serverHost;
    private final int serverPort;
    private Socket socket;

    public Client(String serverHost, int serverPort) {
        this.serverHost = serverHost;
        this.serverPort = serverPort;
    }

    public void connect() throws IOException {
        this.socket = new Socket(this.serverHost, this.serverPort);
    }

    public void request() {
        while (true) {
            try {
                if (socket == null) {
                   this.connect();
                }
                String msg = "%s:hello server.";
                final String sendMsg = String.format(msg, new Date());
                log.info("send msg: {}", sendMsg);
                final OutputStream outputStream = this.socket.getOutputStream();
//                final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new DataOutputStream(outputStream));
//                bufferedOutputStream.write(sendMsg.getBytes(StandardCharsets.UTF_8));
//                bufferedOutputStream.flush();
                final DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
                dataOutputStream.writeInt(sendMsg.length());
                dataOutputStream.write(sendMsg.getBytes(StandardCharsets.UTF_8));
                dataOutputStream.flush();
                TimeUnit.SECONDS.sleep(3);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        final Client client = new Client("127.0.0.1", 3333);
        client.connect();
        client.request();
    }

}
